package com.wanlian.router.ui.router;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.smart.android.ui.BaseActivity;
import com.smart.android.ui.app.IntentExtra;
import com.smart.android.ui.app.IntentResult;
import com.wanlian.router.BuildConfig;
import com.wanlian.router.MainActivity;
import com.wanlian.router.R;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.internal.INetCallBack;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Hyu on 2018/9/12.
 * Email: fvaryu@qq.com
 */
@RuntimePermissions
public class RouterDeviceSettingActivity extends BaseActivity {
    @BindView(R.id.tv_next)
    TextView mNext;
    @BindView(R.id.tv_tip)
    TextView tv_tip;
    private int step;
    @BindView(R.id.tv_ignore)
    TextView tv_ignore;

    @BindView(R.id.image_bind_3_yes)
    ImageView image_bind_3_yes;
    @BindView(R.id.image_bind_3)
    ImageView image_bind_3;

    @BindView(R.id.image_bind_1_yes)
    ImageView image_bind_1_yes;
    @BindView(R.id.image_bind_1)
    ImageView image_bind_1;


    @BindView(R.id.image_bind_2_yes)
    ImageView image_bind_2_yes;
    @BindView(R.id.image_bind_2)
    ImageView image_bind_2;

    @BindView(R.id.line1)
    View line1;
    @BindView(R.id.line2)
    View line2;

    @BindView(R.id.tv_error)
    TextView tv_error;

    @Override
    protected int layout() {
        return R.layout.activity_router_device_setting;
    }

    @Override
    public void initUI() {
        super.initUI();
    }

    boolean isFromLogin() {
        return getIntent().getBooleanExtra(IntentExtra.EXTRA_BOOL, false);
    }

    @Override
    public void initData() {
        super.initData();

        if (isFromLogin()) {
            tv_ignore.setVisibility(View.VISIBLE);
        }

//        int type = NetWrapper.getNetworkType(this);
//        if (type >= 0 && ConnectivityManager.TYPE_WIFI == type) {
        mNext.setText("绑定设备");
        step = 0;
//        }
    }

    @OnClick(R.id.tv_next)
    void next() {
        switch (step) {
            case 0: {
//                Intent intent = new Intent(this, NetworkSettingActivity.class);
//                intent.putExtra(IntentExtra.EXTRA_BOOL, true);
//                startActivityForResult(intent, 101);
                RouterDeviceSettingActivityPermissionsDispatcher.openCameraWithPermissionCheck(this);

            }
            break;
            case 1: {
                toWifiSetting();
            }
            break;
            case 2: {
                RouterDeviceSettingActivityPermissionsDispatcher.locationWithPermissionCheck(this);
            }
            break;
            case 3: {
                redirectActivity(MainActivity.class);
                finish();
            }
            break;
        }

    }

    @OnClick(R.id.tv_ignore)
    void tv_ignore() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 100) {
                step++;
                mNext.setText("去连接WiFi");
                tv_tip.setVisibility(View.VISIBLE);

                image_bind_1.setImageResource(R.drawable.image_bind_1_p);
                image_bind_1_yes.setVisibility(View.VISIBLE);
                line1.setBackgroundColor(Color.parseColor("#29A8FA"));

            } else if (requestCode == 101) {
                step++;
                mNext.setText("开启智能路由新生活");
                image_bind_3.setImageResource(R.drawable.image_bind_3_p);
                image_bind_3_yes.setVisibility(View.VISIBLE);
            }
        }

        if (requestCode == 102) {

            tv_error.setVisibility(View.GONE);
            WifiManager wifiManager = (WifiManager) getApplication().getApplicationContext().getSystemService(WIFI_SERVICE);
            if (!wifiManager.isWifiEnabled()) {
                tv_error.setVisibility(View.VISIBLE);
                showToast("请连接天翼链路由器WiFi");
                return;
            }
            WifiConfiguration wifiConfigurationCurrent = null;
            for (WifiConfiguration wifiConfiguration : wifiManager.getConfiguredNetworks()) {
                if (wifiConfiguration.status == WifiConfiguration.Status.CURRENT) {
                    wifiConfigurationCurrent =wifiConfiguration;
                    break;
                }
            }
            if (wifiConfigurationCurrent == null) {
                tv_error.setVisibility(View.VISIBLE);
                return;
            }
            if (wifiConfigurationCurrent.SSID == null) {
                tv_error.setVisibility(View.VISIBLE);
                return;
            }

            if (!wifiConfigurationCurrent.SSID.startsWith("TianYiLianWiFi")) {
                tv_error.setVisibility(View.VISIBLE);
                return;
            }

            step++;
            mNext.setText("立即配置");
            tv_tip.setVisibility(View.GONE);

            image_bind_2.setImageResource(R.drawable.image_bind_2_p);
            image_bind_2_yes.setVisibility(View.VISIBLE);

            line2.setBackgroundColor(Color.parseColor("#29A8FA"));
        }
    }

    private void toWifiSetting() {
        try {
            Intent intent = new Intent();
            intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
            startActivityForResult(intent, 102);
        } catch (Exception e) {
            showToast("请进入设置连接Wifi");
        }

    }

    void ask() {
        new AlertDialog.Builder(this)
                .setTitle("权限申请")
                .setMessage("请开启定位权限，获取Wifi信息")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).setPositiveButton("去设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                try {
                    Intent i = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + BuildConfig.APPLICATION_ID));
                    startActivity(i);
                } catch (Exception e) {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
                    startActivity(intent);
                }
                finish();
            }
        }).setCancelable(false).create().show();
    }

    @NeedsPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
    void location (){
        Intent intent = new Intent(this, NetworkSettingActivity.class);
        intent.putExtra(IntentExtra.EXTRA_BOOL, true);
        startActivityForResult(intent, 101);
    }

    @OnNeverAskAgain(Manifest.permission.ACCESS_COARSE_LOCATION)
    void onNeverAskAgainReadPhone() {
        ask();
    }

    @OnPermissionDenied(Manifest.permission.ACCESS_COARSE_LOCATION)
    void onDeniedForReadPhone() {
        ask();
    }

    @OnShowRationale(Manifest.permission.ACCESS_COARSE_LOCATION)
    void showRationaleForReadPhone(final PermissionRequest request) {
        permissionWarn("请开启定位权限，获取Wifi信息");
    }


    private void permissionWarn(String message) {
        new AlertDialog.Builder(this)
                .setTitle("权限申请")
                .setMessage(message)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).setPositiveButton("去设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
                startActivity(intent);
                finish();
            }
        }).setCancelable(false).create().show();
    }

    void askCamera() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.ask_permission)
                .setMessage(R.string.tip_camera_permission)
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).setPositiveButton(R.string.to_setting, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
                startActivity(intent);
                finish();
            }
        }).setCancelable(false).create().show();
    }




    @NeedsPermission(Manifest.permission.CAMERA)
    void openCamera() {
        Intent intent = new Intent(this, BindDeviceActivity.class);
        intent.putExtra(IntentExtra.EXTRA_BOOL, true);
        startActivityForResult(intent, 100);
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setTitle(R.string.ask_permission)
                .setMessage(R.string.tip_camera_permission)
                .setNegativeButton(R.string.button_deny, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        request.cancel();
                    }
                }).setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                request.proceed();
            }
        }).setCancelable(false).create().show();
    }


    @OnPermissionDenied(Manifest.permission.CAMERA)
    void onDeniedForLocation() {
        askCamera();
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void onNeverAskAgain() {
        askCamera();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        RouterDeviceSettingActivityPermissionsDispatcher.onRequestPermissionsResult(this,requestCode, grantResults);
//        UserProfileActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


}
